package com.downhometech.productcalculator.activities;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.downhometech.productcalculator.controllers.ProductController;
import com.downhometech.productcalculator.models.Cart;
import com.downhometech.productcalculator.models.CartItem;
import com.downhometech.productcalculator.models.Product;

public class ProductDescriptionActivity extends DefaultActivity
{
	private Product passedInProduct = null;
	private CartItem cartItem = null;
	private Cart cart = null;
	private boolean isUpdateMode = false;

	private double price = 0;
	
	private EditText qtyField = null;
	private EditText discountField = null;
	private CheckBox discountIsPercent = null;
	private TextView nameField = null;
	private RadioButton listedPriceField = null;
	private RadioButton customPriceField = null;
	private RadioGroup productPriceGroup = null;
	private TextView totalPriceField = null;
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.productdescription);

		ProductCalculator application = ((ProductCalculator)getApplicationContext());
		cart = application.getProductCart();	     

		Bundle passedInBundle = this.getIntent().getExtras();
		int productId = passedInBundle.getInt("_productId");
		cartItem = (CartItem)passedInBundle.getSerializable("_cartItem");
		
		ProductController controller = new ProductController(this);
		
		if (cartItem != null) //we're doing an update
		{
			passedInProduct = cartItem.getProduct();
			isUpdateMode = true;
		}
		else //this is a new item
		{
			passedInProduct = controller.getProductById(productId);
			cartItem = new CartItem();
			cartItem.setQuantity(1); //set qty to prefill field
			cartItem.setListPriceUsed(false);
			isUpdateMode = false;
		}
		

		nameField = (TextView) findViewById(R.id.NameText);
		productPriceGroup = (RadioGroup) findViewById(R.id.ProductPriceGroup);
		listedPriceField = (RadioButton) findViewById(R.id.ListedPriceText);
		customPriceField = (RadioButton) findViewById(R.id.CustomPriceText);
		totalPriceField = (TextView) findViewById(R.id.TotalPrice);
		
		qtyField = (EditText) findViewById(R.id.FieldQty);
		discountField = (EditText) findViewById(R.id.FieldDiscount);
		discountIsPercent = (CheckBox)findViewById(R.id.FieldDiscountIsPercent);
		
		price = passedInProduct.getPrice();
		
		nameField.setText(passedInProduct.getName());
		
		listedPriceField.setText(ProductController.formatCurrency(passedInProduct.getListedPrice()));
		listedPriceField.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				recalculateTotalPrice();
			}
		});

		if (passedInProduct.isUserConfigured() && passedInProduct.getCustomPrice() > 0) 
		{
			customPriceField.setText(ProductController.formatCurrency(passedInProduct.getCustomPrice()));
			customPriceField.setChecked(!cartItem.isListPriceUsed());
			listedPriceField.setChecked(cartItem.isListPriceUsed());
		}
		else
		{
			productPriceGroup.removeView(customPriceField);
			listedPriceField.setChecked(true);
		}

		
		totalPriceField.setText(ProductController.formatCurrency(passedInProduct.getPrice()));
		qtyField.setText(cartItem.getQuantity() + "");
		
		qtyField.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				recalculateTotalPrice();
			}
		});
		
		discountIsPercent.setChecked(cartItem.isDiscountAPercentage());
		discountField.setText(cartItem.getDiscount() + "");
		
		discountField.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean hasFocus) 
			{
				double discount = ProductController.getDouble(discountField);
				if (discount == 0 && hasFocus) { discountField.setText("0"); }
				if (!hasFocus) { recalculateTotalPrice(); }
			}
		});
		
		discountIsPercent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton button, boolean buttonChecked) {
				recalculateTotalPrice();
			}
		});
		
		Button cancelButton = (Button) findViewById(R.id.CancelButton);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view)  {
				Intent intent = new Intent(ProductDescriptionActivity.this, CartActivity.class);
				startActivity(intent);
			}
		});
		
		Button removeFromCartButton = (Button) findViewById(R.id.RemoveProductButton);
		removeFromCartButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view)  {
				cart.removeCartItem(cartItem);
				finish();
				Intent intent = new Intent(ProductDescriptionActivity.this, ShowCartActivity.class);
				startActivity(intent);
			}
		});		
		//we don't need to see the remove item button if the item
		//	isn't in the cart yet
		if (!isUpdateMode) { ((LinearLayout)findViewById(R.id.ProductDescriptionButtonRow)).removeView(removeFromCartButton); }
		
		
		Button addToCart = (Button) findViewById(R.id.AddProductButton);
		if (isUpdateMode) { addToCart.setText(getString(R.string.UpdateProductInCart)); } 
		addToCart.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View view) 
			{
				double qty = ProductController.getDouble(qtyField);
				double disc = ProductController.getDouble(discountField);

				if (disc >= 0 && qty >= 0)
				{
					CartItem item = new CartItem(passedInProduct, qty, disc, discountIsPercent.isChecked(), listedPriceField.isChecked());
					if (isUpdateMode) { cart.updateCartItem(item); }
					else { cart.addCartItem(item); }
					
					finish();
					Intent intent = new Intent(ProductDescriptionActivity.this, ShowCartActivity.class);
					startActivity(intent);
				}
			}
		});

	}
		
	private void recalculateTotalPrice()
	{
		CartItem tempItem = new CartItem();
		tempItem.setDiscount(ProductController.getDouble(discountField));
		tempItem.setDiscountAPercentage(discountIsPercent.isChecked());
		tempItem.setQuantity(ProductController.getDouble(qtyField));
		tempItem.setListPriceUsed(listedPriceField.isChecked());
		tempItem.setProduct(passedInProduct);
		totalPriceField.setText(ProductController.formatCurrency(tempItem.getTotalPrice()));
	}
	
	private void buildDialog(String whatDialog)
	{
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		final String constWhatDialog = whatDialog;
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		input.setFocusable(true);
		alert.setView(input);
		
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
		{
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString().trim();
				//Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
				if (constWhatDialog.equals("qty")) qtyField.setText(value + "");
				else if(constWhatDialog.equals("description")) qtyField.setText(value + "");
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
	}
	
	
	//Add the menu system 
	public boolean onCreateOptionsMenu(Menu menu)
	{
		 MenuInflater inflater = getMenuInflater();
		 inflater.inflate(R.menu.menu_productdescription, menu);
		 return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		Intent intent = null;
		switch(item.getItemId())
		{
			case R.id.menu_editDefaultValues:
				intent = new Intent(this, EditSettingsActivity.class);
				startActivity(intent);	 
				finish();
				return true;
			case R.id.menu_goHome:
				intent = new Intent(this, CartActivity.class);
				startActivity(intent);	 
				finish();
				return true; 
			case R.id.menu_editProduct:
				intent = new Intent(this, EditProductActivity.class);
				intent.putExtra("_productId", new Integer(passedInProduct.getId()));
				startActivity(intent);	 
				finish();
				return true; 				
		}
		return false;
	}
}
